/**
 * 
 */
package com.gmail.blackdog1987.onedollar.service.impl;

import com.alibaba.fastjson.JSON;
import com.gmail.blackdog1987.onedollar.dao.*;
import com.gmail.blackdog1987.onedollar.entity.*;
import com.gmail.blackdog1987.onedollar.entity.base.Page;
import com.gmail.blackdog1987.onedollar.service.OrderService;
import com.gmail.blackdog1987.onedollar.util.ErrorCode;
import com.gmail.blackdog1987.onedollar.util.JsonChangeUtil;
import com.gmail.blackdog1987.onedollar.vo.*;
import com.gmail.blackdog1987.onedollar.web.controller.AlipayController;
import com.gmail.blackdog1987.onedollar.web.controller.WXPayController;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 
 * @author 董国超
 *
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderDao orderDao;
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private AddressDao addressDao;
	@Autowired
	private GoodsPriceDao goodsPriceDao;
	@Autowired
	private OrderGoodsDao orderGoodsDao;
	@Autowired
	private OrderRefoundDao orderRefoundDao;
	@Autowired
	private GoodsJudgeDao goodsJudgeDao;
	@Autowired
	private AlipayCallbackDao alipayCallbackDao;
	@Autowired
	private OrderOneDollarDao orderOneDollarDao;
	@Autowired
	private GoodsOneDollarDao goodsOneDollarDao;
	@Autowired
	private OneDollarTicketDao oneDollarTicketDao;
	@Autowired
	private UserChargeDao userChargeDao;
	@Autowired
	private CartDao cartDao;
	@Autowired
	private WXPayCallbackDao wxPayCallbackDao;

	protected final Log logger = LogFactory.getLog(this.getClass());

	@Override
	public Map<String, Object> get(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String status = filter.get("status");		// 0全部 1待评价 2待付款 3待收货 4待发货 5退货
		String userid = filter.get("userid");
		String pageIndex = filter.get("pageindex");
		String pageSize = filter.get("pagesize");
		int index = 1;
		int size = 10;
		if(pageIndex!=null&&pageIndex.length()!=0){
			index = Integer.valueOf(pageIndex);
			if(index<1){
				index = 1;
			}
		}
		if(pageSize!=null&&pageSize.length()!=0){
			size = Integer.valueOf(pageSize);
			if(size==0){
				size = 10;
			}
		}

		Page<OrderVO> datas;
		int statusInt = Integer.valueOf(status);
		if(statusInt==0){
			datas = orderDao.queryByUserid(userid, index, size);
		}else if(statusInt==1){
			datas = orderDao.queryNotCommentByUserid(userid, index, size);
		} else if(statusInt==2){
			datas = orderDao.queryNotPayByUserid(userid, index, size);
		} else if(statusInt==3){
			datas = orderDao.queryNotFinishByUserid(userid, index, size);
		} else if(statusInt==4){
			datas = orderDao.queryNotShipedByUserid(userid, index, size);
		} else if(statusInt==5){
			datas = orderDao.queryRefoundByUserid(userid, index, size);
		} else{
			return JsonChangeUtil.setResultJson(ErrorCode.UNKNOWN, "发生未知错误").getResultMap();
		}
		resultJson.put("data", datas);
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> createOrder(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String goodsinfo = filter.get("goodsinfo");		// json传递商品参数，参考OrderGoodsVO,商品的集合
		String userid = filter.get("userid");
		String time = filter.get("time");
		String type = filter.get("type");
		String addressid = filter.get("addressid");
		String postscript = filter.get("postscript");

		TOrderInfoEntity info = new TOrderInfoEntity();
		if(addressid==null||addressid.length()==0){
			return JsonChangeUtil.setResultJson(ErrorCode.ORDER_INVALIDGOODS, "请选择收货地址").getResultMap();
		}
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		TUserAddressEntity address = addressDao.get(Integer.valueOf(addressid));
		info.setAddress(address.getAddress());
		info.setAddTime(new Timestamp(System.currentTimeMillis()));
		info.setConsignee(address.getReceiver());
		info.setPostscript(postscript);
//		info.setPayId(1);
//		info.setDistrict(address.getArea());
		info.setDistrict(address.getArea()==null||address.getArea()==0?address.getCity():address.getArea());
		info.setMobile(address.getPhone());
		info.setOrderStatus(1);
		info.setShippingStatus(0);
		info.setPayTime(new Timestamp(System.currentTimeMillis()));
		info.setPayStatus(0);
		info.setJudgeStatus(0);
		info.setIsRefund(0);
		info.setZipcode(address.getPostCode());
		info.setTel(address.getPhone());
		info.setProcessMode(0);
		info.setOperator("手机下单");
		info.setType(Integer.valueOf(type));
		info.setInvalid(0);

		// 根据goodsinfo算出价格,不同的商品
		List<OrderGoodsVO> goodsVOs;
		if(goodsinfo!=null&&goodsinfo.trim().length()!=0){
			goodsVOs = JSON.parseArray(goodsinfo, OrderGoodsVO.class);
		}else{
			return JsonChangeUtil.setResultJson(ErrorCode.ORDER_INVALIDGOODS, "请选择正确的商品！或者刷新后重试！").getResultMap();
		}

		List<TOrderGoodsEntity> goodsEntities = new ArrayList<TOrderGoodsEntity>(goodsVOs.size());
		BigDecimal amount = new BigDecimal(0);
		BigDecimal oldAmount = new BigDecimal(0);
		String [] priceIds = new String[goodsVOs.size()];

		Map<Integer, Integer> tmp = new HashMap<Integer, Integer>();


		System.out.println("```````````````````````\ngoods info : "+filter);

		int i = 0; // pos下标
		for (OrderGoodsVO vo: goodsVOs){
			TOrderGoodsEntity entity = new TOrderGoodsEntity();
			entity.setGoodsId(vo.getGoodsId());
			if(tmp.containsKey(vo.getGoodsId())){
				tmp.put(vo.getGoodsId(), 1);
			}else{
				tmp.put(vo.getGoodsId(), tmp.get(vo.getGoodsId()));
			}
			entity.setGoodsName(vo.getGoodsName());
			entity.setGoodsPrice(vo.getGoodsPrice());
			entity.setGoodsAttr(vo.getGoodsAttr());
			entity.setMarketPrice(vo.getMarketPrice());
			entity.setGoodsNumber(vo.getGoodsNumber());
			entity.setPriceId(vo.getPriceId());
			priceIds[i] = String.valueOf(vo.getPriceId());
			goodsEntities.add(entity);
			amount = amount.add(vo.getGoodsPrice().multiply(new BigDecimal(vo.getGoodsNumber())));
			oldAmount = oldAmount.add(vo.getMarketPrice().multiply(new BigDecimal(vo.getGoodsNumber())));
			i++;
		}
//		String ids = "";
//		for(Integer id: tmp.keySet()){
//			ids+=(","+id);
//		}
//		ids = ids.replaceFirst(",","");
//		List<TGoodsEntity> goods  = goodsDao.queryByIds(ids);
//		for (TGoodsEntity g : goods){
//			g.setSoldnumber((g.getSoldnumber()==null?0:g.getSoldnumber()) + tmp.get(g.getGoodsId()));
//		}
//		goodsDao.saveAll(goods);

		List<TGoodsPriceEntity> prices = goodsPriceDao.queryByIds(priceIds);
		List<TGoodsPriceEntity> pricesAvailable = new ArrayList<TGoodsPriceEntity>();
		for (OrderGoodsVO vo: goodsVOs){
			for(TGoodsPriceEntity price : prices){
				if(vo.getPriceId().intValue()!=price.getId()){
					continue;
				}

				// 是否下架
				TGoodsEntity g = goodsDao.get(price.getGoodsId());
				if(g.getIsShelves()==0) {
					return JsonChangeUtil.setResultJson(ErrorCode.ORDER_INVALIDGOODS, g.getGoodsName() + "已经下架！ ").getResultMap();
				}

				if(vo.getGoodsNumber() > price.getNumber()){
					if(price.getNumber().intValue()>0){
						return JsonChangeUtil.setResultJson(ErrorCode.ORDER_INVALIDGOODS, vo.getGoodsName() + "数量不足！您最多还能购买 " + price.getNumber() + "个!").getResultMap();
					}
					return JsonChangeUtil.setResultJson(ErrorCode.ORDER_INVALIDGOODS, vo.getGoodsName() + " 已经售罄！ ").getResultMap();
				}
//				else{
//					price.setNumber(price.getNumber()-vo.getGoodsNumber());
//					pricesAvailable.add(price);
//				}
			}
		}
		goodsPriceDao.saveAll(pricesAvailable);
		info.setGoodsAmount(oldAmount);
		info.setOrderAmount(amount);
		info.setActualAmount(amount);
		info.setBestTime(time);
		info.setUserId(Integer.valueOf(userid));
		Integer orderid = (Integer) orderDao.create(info);
		for (TOrderGoodsEntity entity: goodsEntities){
			entity.setOrderId(orderid);
		}
		orderGoodsDao.saveAll(goodsEntities);

//		List<TOrderGoodsEntity> goods = orderGoodsDao.findBy("orderId",Integer.valueOf(order.getOrderId()));
		List<TGoodsCartEntity> car = cartDao.findBy("userId", Integer.valueOf(userid));
		List<TGoodsCartEntity> carDel = new ArrayList<TGoodsCartEntity>();
		for(int index = 0; index < goodsVOs.size(); index++){
			for(int j = 0; j < car.size(); j++){
				TGoodsCartEntity c = car.get(j);
				if(goodsVOs.get(index).getPriceId()!=null&&c.getPriceId()!=null&&goodsVOs.get(index).getPriceId().intValue() == c.getPriceId().intValue() && goodsVOs.get(index).getGoodsId().intValue() == c.getGoodsId().intValue()){
					carDel.add(c);
				}
			}
		}
		if(carDel.size()!=0){
			cartDao.removeAll(carDel);
		}

		String ids = seperateOrder(info);
		if(ids!=null&&ids.length()!=0){
			resultJson.put("data", ids);
		}else{
			resultJson.put("data", info.getOrderId());
		}
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> deleteOrder(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String orderid = filter.get("orderid");		// json传递商品参数
		String userid = filter.get("userid");
		TOrderInfoEntity order = orderDao.get(Integer.valueOf(orderid));
		if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}
		order.setInvalid(-1);
		order.setFinishTime(new Timestamp(System.currentTimeMillis()));
		orderDao.update(order);
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doRefound(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String orderid = filter.get("orderid");		// json传递商品参数
		String userid = filter.get("userid");
		String reason = filter.get("reason");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		TOrderInfoEntity order = orderDao.get(Integer.valueOf(orderid));

		if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}
		if(order.getIsRefund()!=null&&order.getIsRefund()!=0){
			return JsonChangeUtil.setResultJson(ErrorCode.ORDER_REFOUNDING, "您已经申请过退款").getResultMap();
		}
		TOrderRefundEntity entity = new TOrderRefundEntity();
		entity.setUserId(Integer.valueOf(userid));
		entity.setOrderId(Integer.valueOf(orderid));
		entity.setAddTime(new Timestamp(System.currentTimeMillis()));
		entity.setMemo(reason);
		entity.setStatus(3);
		entity.setType(0);
		entity.setRefundReason(reason);
		entity.setRefundAmount(order.getOrderAmount());
		orderRefoundDao.create(entity);
		order.setIsRefund(1);
		orderDao.update(order);
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doCancel(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String orderid = filter.get("orderid");		// json传递商品参数
		String userid = filter.get("userid");
		TOrderInfoEntity order = orderDao.get(Integer.valueOf(orderid));
		if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}
		order.setOrderStatus(2);
		order.setFinishTime(new Timestamp(System.currentTimeMillis()));
		order.setInvalid(-1);
		orderDao.update(order);
		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> updateForReceiveOrder(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String orderid = filter.get("orderid");		// json传递商品参数
		String userid = filter.get("userid");
		TOrderInfoEntity order = orderDao.get(Integer.valueOf(orderid));
		if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue() || order.getOrderStatus()!=1 || order.getShippingStatus()!=1){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}
		order.setShippingStatus(2);
		order.setOrderStatus(5);
		order.setFinishTime(new Timestamp(System.currentTimeMillis()));
		orderDao.update(order);
		TUserEntity userEntity = userDao.get(Integer.valueOf(userid));
		if(userEntity.getReferenceId()!=null&&userEntity.getReferenceId()!=0){
			TUserEntity referenceUser = userDao.get(Integer.valueOf(userEntity.getReferenceId()));
			if(referenceUser!=null&&(order.getOnedollarId()==null||order.getOnedollarId()==0)){	// 不能是一元/十元
				BigDecimal bonus = order.getActualAmount()==null?new BigDecimal(0):order.getActualAmount();
				bonus = bonus.multiply(new BigDecimal(0.065)).setScale(2, RoundingMode.DOWN);
				if(bonus.doubleValue()==0){
					bonus = new BigDecimal(0.01);
				}
				referenceUser.setMoney(referenceUser.getMoney()==null?bonus:referenceUser.getMoney().add(bonus).setScale(2, RoundingMode.DOWN));
				referenceUser.setIncomeNow(referenceUser.getIncomeNow()==null?bonus:referenceUser.getIncomeNow().add(bonus).setScale(2, RoundingMode.DOWN));
				referenceUser.setIncomeTotal(referenceUser.getIncomeTotal()==null?bonus:referenceUser.getIncomeTotal().add(bonus).setScale(2, RoundingMode.DOWN));
				userDao.update(referenceUser);

				TUserChargeEntity chargeEntity = new TUserChargeEntity();
				chargeEntity.setUserId(referenceUser.getUserId());
				chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
				chargeEntity.setValue(bonus);
				chargeEntity.setType(0);
				chargeEntity.setChannel(6);
				userChargeDao.create(chargeEntity);
			}
		}
		return resultJson.getResultMap();
	}

	@Override
	public  Map<String, Object> createOneDollarOrder(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");
		String onedollarid = filter.get("onedollarid");		// json传递商品参数，参考OrderGoodsVO
		String userid = filter.get("userid");
		String count = filter.get("count");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}

		TGoodsOnedollarEntity onedollarEntity = goodsOneDollarDao.get(Integer.valueOf(onedollarid));
		System.out.println("======getNeed |||||  count====="+onedollarEntity.getNeed()+"  |||||||||  "+count);

		if(onedollarEntity==null||onedollarEntity.getEndtime()!=null){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "活动已经结束").getResultMap();
		}
		if(onedollarEntity.getFromtime().getTime()>System.currentTimeMillis()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "活动还未开始").getResultMap();
		}
		//Need是总名额数
		//Fill是报名
		if(onedollarEntity.getFill()>(onedollarEntity.getNeed()/onedollarEntity.getPercent())){
			System.out.println("nom num:" + onedollarEntity.getFill() + " total num:" + onedollarEntity.getNeed());
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "名额已满").getResultMap();
		}

		if(onedollarEntity.getFill()==null||onedollarEntity.getFill()==0){
			onedollarEntity.setFirsttime(new Timestamp(System.currentTimeMillis()));
		}

		Double percentDouble = onedollarEntity.getPercent()==null||onedollarEntity.getPercent()==0?1:onedollarEntity.getPercent();
		int available = (int)(Double.valueOf(onedollarEntity.getNeed())/percentDouble) - onedollarEntity.getFill();

		if(available < Integer.valueOf(count)){
			System.out.println("======available <<<<<<  count=====" + available + "  <<<<<<<<<<  " + count);

			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "数量不足").getResultMap();
		}

		if(available == Integer.valueOf(count)){

			System.out.println("======available ============  count====="+available+"  ============  "+count);
	//		count = available + "";
			// 买完了，把开奖时间提前
//			Calendar c = Calendar.getInstance();
//			c.add(Calendar.MINUTE, 10);
			onedollarEntity.setTotime(new Timestamp(System.currentTimeMillis()));
//			onedollarEntity.setLasttime(new Timestamp(System.currentTimeMillis()));
		}
		System.out.println("======available :::  count====="+available+"  :: "+count);
		List<TOrderOnedollarEntity> ticket = orderOneDollarDao.queryNewest(Integer.valueOf(onedollarid), Integer.valueOf(count));

		if(ticket==null||ticket.isEmpty()){
			System.out.println("ticket is null");
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "名额已满").getResultMap();
		}

		for (TOrderOnedollarEntity orderOnedollarEntity: ticket){
			orderOnedollarEntity.setUserId(Integer.valueOf(userid));
			orderOnedollarEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
			orderOnedollarEntity.setOnedollarId(Integer.valueOf(onedollarid));
			orderOnedollarEntity.setPayStatus(1);
			orderOnedollarEntity.setPayType(0);
		}
//		if(onedollarEntity.getFill()!=null && onedollarEntity.getNeed() !=null && onedollarEntity.getFill() >= onedollarEntity.getNeed()/percentDouble){
//			onedollarEntity.setLasttime(new Timestamp(System.currentTimeMillis()));
//		}
		onedollarEntity.setFill(onedollarEntity.getFill() == null ? Integer.valueOf(count) : onedollarEntity.getFill() + Integer.valueOf(count));
		goodsOneDollarDao.save(onedollarEntity);

		ticket.get(0).setTicketCodeEnd(ticket.get(0).getTicketCode() + Integer.valueOf(count) - 1);
		orderOneDollarDao.updateBuyByIds(Integer.valueOf(userid), Integer.valueOf(onedollarid), Integer.valueOf(count));

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> createExchangeOneDollarOrder(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String onedollarid = filter.get("onedollarid");		// json传递商品参数，参考OrderGoodsVO
		String userid = filter.get("userid");
		String time = filter.get("time");
		String type = filter.get("type");
		String addressid = filter.get("addressid");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}

		TGoodsOnedollarEntity onedollarEntity = goodsOneDollarDao.get(Integer.valueOf(onedollarid));

		TOrderInfoEntity info = new TOrderInfoEntity();
		TUserAddressEntity address = addressDao.get(Integer.valueOf(addressid));
		info.setAddress(address.getAddress());
		info.setPayId(0);
		info.setAddTime(new Timestamp(System.currentTimeMillis()));
		info.setConsignee(address.getReceiver());
		info.setDistrict(address.getArea()==null||address.getArea()==0?address.getCity():address.getArea());
		info.setMobile(address.getPhone());
		info.setOrderStatus(1);
		info.setType(onedollarEntity.getType());
		info.setOnedollarId(Integer.valueOf(onedollarid));
		info.setShippingStatus(0);
		info.setPayStatus(1);
		info.setPayTime(new Timestamp(System.currentTimeMillis()));
		info.setJudgeStatus(0);
		info.setIsRefund(0);
		info.setZipcode(address.getPostCode());
		info.setTel(address.getPhone());
		info.setProcessMode(0);
		info.setOperator("手机下单");
//		info.setType(Integer.valueOf(type));
		info.setInvalid(0);
		info.setOrderAmount(new BigDecimal("10".equals(onedollarEntity.getType())?10:1));

		// 这个人这次活动中了几注
		Map<String ,Object> params = new HashMap<String, Object>();
		params.put("onedollarId", Integer.valueOf(onedollarid));
		params.put("win",1);
		params.put("userId",Integer.valueOf(userid));
		params.put("status!=",1);
		List<TOnedollarTicketEntity> tickets = oneDollarTicketDao.find(params);
		if(tickets==null||tickets.size()==0){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您没有可以兑奖的奖券或者已经申请过兑奖！如有疑问请咨询我们").getResultMap();
		}
		TGoodsEntity goods = goodsDao.queryOneDollar(Integer.valueOf(onedollarid));
		info.setGoodsAmount(goods.getDefaultPrice().multiply(new BigDecimal(tickets.size())));
		info.setOrderAmount(new BigDecimal(0));
		info.setActualAmount(new BigDecimal(0));
		info.setBestTime(time);
		info.setUserId(Integer.valueOf(userid));

		int payType = 0;
		for (TOnedollarTicketEntity ticket : tickets){
			ticket.setStatus(1);
			// 维护订单支付方式
		}
		// 这个人这次活动中了几注
		Map<String ,Object> orderOneDollarParam = new HashMap<String, Object>();
		orderOneDollarParam.put("onedollarId", Integer.valueOf(onedollarid));
		orderOneDollarParam.put("ticketCode",tickets.get(0).getCode());
		orderOneDollarParam.put("userId",Integer.valueOf(userid));

		List<TOrderOnedollarEntity> orderOnedollarEntity = orderOneDollarDao.find(orderOneDollarParam);
		if(orderOnedollarEntity!=null&&!orderOnedollarEntity.isEmpty()){
			info.setPayId(orderOnedollarEntity.get(0).getPayType());
		}
		oneDollarTicketDao.saveAll(tickets);

		Integer orderid = (Integer) orderDao.create(info);

		TOrderGoodsEntity entity = new TOrderGoodsEntity();
		entity.setGoodsId(goods.getGoodsId());
		entity.setGoodsName(goods.getGoodsName());
		entity.setGoodsPrice(goods.getDefaultPrice());
		entity.setGoodsAttr(onedollarEntity.getName());
		entity.setMarketPrice(goods.getDefaultPrice());
		entity.setGoodsNumber(tickets.size());
		entity.setOrderId(orderid);
		orderGoodsDao.create(entity);

		resultJson.put("data", info);

		return resultJson.getResultMap();
	}

	@Override
	public Map<String, Object> doPayOneDollar(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String id = filter.get("id");
		String userid = filter.get("userid");
		String payamount = filter.get("payamount");

//		TOrderOnedollarEntity order = orderOneDollarDao.get(Integer.valueOf(orderid));
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		TGoodsOnedollarEntity g = goodsOneDollarDao.get(Integer.valueOf(id));
		int count = Double.valueOf(payamount).intValue() / g.getType();
		List<TOrderOnedollarEntity> orders = orderOneDollarDao.queryByIds(Integer.valueOf(userid), Integer.valueOf(id), count);
		TOrderOnedollarUserEntity orderOnedollarUserEntity = new TOrderOnedollarUserEntity();
		orderOnedollarUserEntity.setUserId(user.getUserId());
		orderOnedollarUserEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		orderOnedollarUserEntity.setCount(orders.size());
		orderOnedollarUserEntity.setHead(user.getHead());
		orderOnedollarUserEntity.setNickName(user.getNickName());
		orderOnedollarUserEntity.setOnedollarId(Integer.valueOf(id));
		orderOneDollarDao.create(orderOnedollarUserEntity);

		for (TOrderOnedollarEntity order: orders){
			if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue() || order.getPayStatus()!=0){
				return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
			}
			order.setPayStatus(1);
			order.setPayType(0);
		}

		count = orders.size();

		double paymountDouble = Double.valueOf(count*g.getType());

		orderOneDollarDao.updatePayByIds(Integer.valueOf(userid), Integer.valueOf(id), count, 0);

		if(user.getMoney().doubleValue() < paymountDouble){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您的余额不足哟").getResultMap();
		}
		user.setMoney(user.getMoney().subtract(new BigDecimal(paymountDouble)));
		userDao.update(user);
		TUserChargeEntity chargeEntity = new TUserChargeEntity();
		chargeEntity.setValue(new BigDecimal(paymountDouble));
		chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		chargeEntity.setChannel(TUserChargeEntity.BUY);
		chargeEntity.setUserId(Integer.valueOf(userid));
		userChargeDao.create(chargeEntity);

		// 分红
		if(user.getReferenceId()!=null&&user.getReferenceId()!=0){
			TUserEntity referenceUser = userDao.get(user.getReferenceId());
			BigDecimal bonus = chargeEntity.getValue().multiply(new BigDecimal(0.065)).setScale(2, RoundingMode.DOWN);
			if(bonus.doubleValue()==0){
				bonus = new BigDecimal(0.01);
			}
			referenceUser.setMoney(referenceUser.getMoney()==null?bonus:referenceUser.getMoney().add(bonus).setScale(2, RoundingMode.DOWN));
			referenceUser.setIncomeNow(referenceUser.getIncomeNow()==null?bonus:referenceUser.getIncomeNow().add(bonus).setScale(2, RoundingMode.DOWN));
			referenceUser.setIncomeTotal(referenceUser.getIncomeTotal()==null?bonus:referenceUser.getIncomeTotal().add(bonus).setScale(2, RoundingMode.DOWN));
			userDao.update(referenceUser);

			TUserChargeEntity chargeEntityBonus = new TUserChargeEntity();
			chargeEntityBonus.setUserId(referenceUser.getUserId());
			chargeEntityBonus.setCreatetime(new Timestamp(System.currentTimeMillis()));
			chargeEntityBonus.setValue(bonus);
			chargeEntityBonus.setType(0);
			chargeEntityBonus.setChannel(6);
			userChargeDao.create(chargeEntityBonus);
		}

		// 判断是不是卖完了，卖完了开奖
		if(orderOneDollarDao.isSoldOut(id)){
			TGoodsOnedollarEntity goods = goodsOneDollarDao.get(Integer.valueOf(id));
			List<TOnedollarTicketEntity> ticket = oneDollarTicketDao.findBy("onedollarId", Integer.valueOf(id));
			if(ticket.size()==0){	// 没有生成奖券
				TOnedollarTicketEntity te = new TOnedollarTicketEntity();
				te.setOnedollarId(Integer.valueOf(id));
				te.setWin(1);
				te.setStatus(0);
				// 设置的所有奖券，都是从10000开始的，所以可以查询最后一个的ticketEnd就知道产生了多少个奖券。

				int randomCode = new Random().nextInt(goods.getNeed());		// 生成随机的步长
				te.setCode(10000001+randomCode);
				TOrderOnedollarEntity winner = orderOneDollarDao.queryWinnerOrder(te.getCode(), orderOnedollarUserEntity.getOnedollarId());
				if(winner==null){	// 如果是空的话，容错，随便再找个人
					winner = orderOneDollarDao.queryRandomWinner(orderOnedollarUserEntity.getOnedollarId());
				}
				te.setUserId(winner.getUserId());
				oneDollarTicketDao.create(te);
			}else{
				if(ticket.size()>0){
					List<TOnedollarTicketEntity> t = new ArrayList<TOnedollarTicketEntity>();
					for (int i = 1; i < ticket.size(); i ++){
						ticket.get(i).setWin(0);
						t.add(ticket.get(i));
					}
					if(t.size()>0){
						oneDollarTicketDao.saveAll(t);
					}
				}
			}

			// 卖完了，维护开奖时间
			Calendar c1 = Calendar.getInstance();
			c1.setTime(goods.getTotime());
			c1.add(Calendar.MINUTE, 3);
			goods.setTotime(new Timestamp(c1.getTimeInMillis()));
			goods.setEndtime(goods.getTotime());
			goods.setFill(goods.getNeed());
			goodsOneDollarDao.save(goods);
		}

		return resultJson.getResultMap();
	}

	@Override
	public void deleteNotPayOneDollarOrder() {
//		Map<String, Object> param = new HashMap<String, Object>();
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MINUTE, -3);
//		param.put("createtime<", c.getTime());
//		param.put("payStatus", 0);
		List<TOrderOnedollarEntity> notPayOrder = orderOneDollarDao.queryNotPayBefore(c.getTime());
		if(notPayOrder==null||notPayOrder.size()==0){
			return;
		}
		List<TGoodsOnedollarEntity> goods = goodsOneDollarDao.queryForReset(c.getTime());
		Map<Integer, Integer> count = new HashMap<Integer, Integer>();
		for (TOrderOnedollarEntity order : notPayOrder){
			if(count.containsKey(order.getOnedollarId())){
				count.put(order.getOnedollarId(), 1 + count.get(order.getOnedollarId()));
			}else{
				count.put(order.getOnedollarId(), 1);
			}
			order.setPayStatus(0);
			order.setUserId(null);
			order.setOrderId(null);
		}
		orderOneDollarDao.saveAll(notPayOrder);

		List<TGoodsOnedollarEntity> goodsForUpdate = new ArrayList<TGoodsOnedollarEntity>();

		for (TGoodsOnedollarEntity g : goods){
			if(count.containsKey(g.getId())){
				g.setFill(g.getFill()-count.get(g.getId()));
				if(g.getFill()<0){
					g.setFill(0);
				}
				goodsForUpdate.add(g);
			}
		}
		if(goodsForUpdate.size()!=0){
			goodsOneDollarDao.saveAll(goodsForUpdate);
		}
	}
//
//	@Override
//	public void deleteNotPayOrder() {
////		Map<String, Object> param = new HashMap<String, Object>();
//		Calendar c = Calendar.getInstance();
//		c.add(Calendar.MINUTE, -3);
////		param.put("createtime<", c.getTime());
////		param.put("payStatus", 0);
//		List<TOrderOnedollarEntity> notPayOrder = orderOneDollarDao.queryNotPayBefore(c.getTime());
//		if(notPayOrder==null||notPayOrder.size()==0){
//			return;
//		}
//		List<TGoodsOnedollarEntity> goods = goodsOneDollarDao.queryForReset(c.getTime());
//		Map<Integer, Integer> count = new HashMap<Integer, Integer>();
//		for (TOrderOnedollarEntity order : notPayOrder){
//			if(count.containsKey(order.getOnedollarId())){
//				count.put(order.getOnedollarId(), 1 + count.get(order.getOnedollarId()));
//			}else{
//				count.put(order.getOnedollarId(), 1);
//			}
//			order.setPayStatus(0);
//			order.setUserId(null);
//			order.setOrderId(null);
//		}
//		orderOneDollarDao.saveAll(notPayOrder);
//
//		List<TGoodsOnedollarEntity> goodsForUpdate = new ArrayList<TGoodsOnedollarEntity>();
//
//		for (TGoodsOnedollarEntity g : goods){
//			if(count.containsKey(g.getId())){
//				g.setFill(g.getFill()-count.get(g.getId()));
//				if(g.getFill()<0){
//					g.setFill(0);
//				}
//				goodsForUpdate.add(g);
//			}
//		}
//		if(goodsForUpdate.size()!=0){
//			goodsOneDollarDao.saveAll(goodsForUpdate);
//		}
//	}

//	@Override
//	public void updateOneDollarWinner() {
//		Calendar c = updateOneDollarWinnerCalendar.getInstance();
//		c.add(Calendar.MINUTE, -10);
//		// 还没有开奖的活动
//		List<TGoodsOnedollarEntity> onedollarEntities = goodsOneDollarDao.queryForFinish(c.getTime());
//		List<TGoodsOnedollarEntity> updateOneDollarEntities = new ArrayList<TGoodsOnedollarEntity>();
//		if(onedollarEntities == null||onedollarEntities.size()==0){
//			return;
//		}
//		// 还没有开奖的活动，但是已经生成了的奖券
//		List<TOnedollarTicketEntity> ticketEntities = oneDollarTicketDao.queryFinished(c.getTime());
////		List<TOnedollarTicketEntity> ticketForGenerate = new ArrayList<TOnedollarTicketEntity>();
//		Map<Integer, TOnedollarTicketEntity> ticketForGenerate = new HashMap<Integer, TOnedollarTicketEntity>();
//		for (TGoodsOnedollarEntity e : onedollarEntities){		// 遍历活动
//			if((e.getFill()==null?0:e.getFill())<((int)(e.getPercent()*(e.getNeed()==null?0:e.getNeed())))){		// 报名人数不够，延长时间
//				if(e.getTotime()==null){
//					Calendar c1 = Calendar.getInstance();
//					c1.add(Calendar.DATE, 1);
//					e.setTotime(new Timestamp(c1.getTimeInMillis()));
//					e.setEndtime(null);
//				}else{
//					Calendar c1 = Calendar.getInstance();
//					c1.setTime(e.getTotime());
//					c1.add(Calendar.DATE, 1);
//					e.setTotime(new Timestamp(c1.getTimeInMillis()));
//					e.setEndtime(null);
//				}
//				updateOneDollarEntities.add(e);
//				continue;
//			}		// 报名人数够了，开奖
//			Calendar c1 = Calendar.getInstance();
//			c1.setTime(e.getTotime());
//			c1.add(Calendar.MINUTE, 3);
//			e.setEndtime(new Timestamp(c1.getTimeInMillis()));
//			e.setTotime(new Timestamp(c1.getTimeInMillis()));
//			boolean foundTicket = false;
//			for (TOnedollarTicketEntity te : ticketEntities){		// 查看奖券，看看是否有生成的，有生成的，标记下来，不自动设置中奖人，否则，生成中奖奖券
//				if(te.getOnedollarId()==e.getId()){			// 有奖券，记录下来
//					foundTicket = true;
//					updateOneDollarEntities.add(e);
//					break;
//				}
//			}
//			if(!foundTicket){
//				TOnedollarTicketEntity te = new TOnedollarTicketEntity();
//				te.setOnedollarId(e.getId());
//				te.setWin(1);
//				te.setStatus(0);
//				// 设置的所有奖券，都是从10000开始的，所以可以查询最后一个的ticketEnd就知道产生了多少个奖券。
//				int randomCode = new Random().nextInt(e.getNeed());		// 生成随机的步长
//				te.setCode(10000001+randomCode);
//				TOrderOnedollarEntity winnerOrder = orderOneDollarDao.queryWinnerOrder(te.getCode(), e.getId());
//				if(winnerOrder==null||winnerOrder.getUserId()==null){	// 如果开奖发现中奖人的ID不对头，就放弃开奖，重新等下一次开奖
//					return;
//				}
//				te.setUserId(winnerOrder.getUserId());
//				updateOneDollarEntities.add(e);
//				ticketForGenerate.put(e.getId(), te);
//			}
//		}
//		if(updateOneDollarEntities!=null&&updateOneDollarEntities.size()!=0){
//			goodsOneDollarDao.saveAll(updateOneDollarEntities);
//		}
//		if(ticketForGenerate!=null&&ticketForGenerate.size()!=0){
//			oneDollarTicketDao.saveAll(ticketForGenerate.values());
//		}
//	}

	@Override
	public Map<String, Object> doPay(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String orderid = filter.get("orderid");		// json传递商品参数
		String userid = filter.get("userid");
		String payamount = filter.get("payamount");
		orderid = orderid.replaceAll("-",",");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		List<TOrderInfoEntity> orders = orderDao.queryByIds(orderid);
		if(orders==null||orders.isEmpty()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}


		for (TOrderInfoEntity order: orders){
			if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue() || order.getPayStatus()!=0){
				return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
			}
			order.setPayStatus(1);
			order.setPayId(0);
			order.setPayTime(new Timestamp(System.currentTimeMillis()));
		}

		if(user.getMoney().doubleValue() < Double.valueOf(payamount)){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您的余额不足哟").getResultMap();
		}
		user.setMoney(user.getMoney().subtract(new BigDecimal(Double.valueOf(payamount))));

		TUserChargeEntity chargeEntity = new TUserChargeEntity();
		chargeEntity.setValue(new BigDecimal(Double.valueOf(payamount)));
		chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		chargeEntity.setChannel(TUserChargeEntity.BUY);
		chargeEntity.setUserId(Integer.valueOf(userid));


		// 支付成功，清除相应的购物车商品
		List<TOrderGoodsEntity> goods = orderGoodsDao.queryByIds(orderid);

		Map<Integer, Integer> priceCount = new HashMap<Integer, Integer>();
		String[] goodsIds = new String[goods.size()];

		Map<Integer, Integer> tmp = new HashMap<Integer, Integer>();

		for(int i = 0; i < goods.size(); i++){
			goodsIds[i] = goods.get(i).getGoodsId().toString();
			priceCount.put(goods.get(i).getPriceId(), goods.get(i).getGoodsNumber());
			if(!tmp.containsKey(goods.get(i).getGoodsId())){
				tmp.put(goods.get(i).getGoodsId(), goods.get(i).getGoodsNumber());
			}else{
				tmp.put(goods.get(i).getGoodsId(), tmp.get(goods.get(i).getGoodsId()) + goods.get(i).getGoodsNumber());
			}
		}
		List<TGoodsPriceEntity> priceEntities = goodsPriceDao.queryByGoodsIds(goodsIds);	// 维护数量
		if(priceEntities!=null){
			for (TGoodsPriceEntity price : priceEntities){
				if(priceCount.containsKey(price.getId())){
					if(price.getNumber()==null||price.getNumber()<priceCount.get(price.getId())){
						TGoodsEntity g = goodsDao.get(price.getGoodsId());
						return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "库存不足，付款失败。"+g.getGoodsName()+"["+getParam(price) + "]"+ "还能购买[" + price.getNumber() +"]个").getResultMap();
					}
					price.setNumber(price.getNumber()-priceCount.get(price.getId()));
				}
			}
			goodsPriceDao.saveAll(priceEntities);
		}
		orderOneDollarDao.saveAll(orders);
		userDao.update(user);
		userChargeDao.create(chargeEntity);

		String ids = "";
		for(Integer id: tmp.keySet()){
			ids+=(","+id);
		}
		ids = ids.replaceFirst(",","");
		List<TGoodsEntity> goodsEntities  = goodsDao.queryByIds(ids);
		for (TGoodsEntity g : goodsEntities){
			g.setSoldnumber((g.getSoldnumber()==null?0:g.getSoldnumber()) + tmp.get(g.getGoodsId()));
		}
		goodsDao.saveAll(goodsEntities);

		return resultJson.getResultMap();
	}

	private String getParam(TGoodsPriceEntity priceEntity){
		String p = "";
		if(priceEntity.getValue1()==null){
			return p;
		}
		p += priceEntity.getValue1() + " ";
		if(priceEntity.getValue2()==null){
			return p;
		}
		p += priceEntity.getValue2() + " ";
		if(priceEntity.getValue3()==null){
			return p;
		}
		p += priceEntity.getValue3() + " ";
		if(priceEntity.getValue4()==null){
			return p;
		}
		p += priceEntity.getValue4() + " ";
		if(priceEntity.getValue5()==null){
			return p;
		}
		p += priceEntity.getValue5() + " ";
		if(priceEntity.getValue6()==null){
			return p;
		}
		p += priceEntity.getValue6() + " ";
		if(priceEntity.getValue7()==null){
			return p;
		}
		p += priceEntity.getValue7() + " ";
		if(priceEntity.getValue8()==null){
			return p;
		}
		p += priceEntity.getValue8() + " ";
		if(priceEntity.getValue9()==null){
			return p;
		}
		p += priceEntity.getValue9() + " ";
		if(priceEntity.getValue10()==null){
			return p;
		}
		p += priceEntity.getValue10() + " ";
		return p;
	}

	private String seperateOrder(TOrderInfoEntity infoEntity){
		List<TOrderGoodsEntity> goodsEntities = orderGoodsDao.findBy("orderId", infoEntity.getOrderId());
		if(goodsEntities==null||goodsEntities.isEmpty()){
			return null;
		}
		String ids = "";
		for (TOrderGoodsEntity goodsEntity : goodsEntities){
			TOrderInfoEntity newOrder = new TOrderInfoEntity();
			newOrder.setInvalid(0);
			newOrder.setType(infoEntity.getType());
			newOrder.setUserId(infoEntity.getUserId());

			newOrder.setMobile(infoEntity.getMobile());
			newOrder.setAddress(infoEntity.getAddress());
			newOrder.setAddTime(infoEntity.getAddTime());
			newOrder.setBestTime(infoEntity.getBestTime());
			newOrder.setConfirmTime(infoEntity.getConfirmTime());
			newOrder.setConsignee(infoEntity.getConsignee());
			newOrder.setDistrict(infoEntity.getDistrict());
			newOrder.setEmail(infoEntity.getEmail());
			newOrder.setFinishTime(infoEntity.getFinishTime());
			newOrder.setGoodsAmount(goodsEntity.getGoodsPrice());
			newOrder.setInsureFee(infoEntity.getInsureFee());
			newOrder.setInvContent(infoEntity.getInvContent());
			newOrder.setInvPayee(infoEntity.getInvPayee());
			newOrder.setIntegralMoney(infoEntity.getIntegralMoney());
			newOrder.setIsRefund(infoEntity.getIsRefund());
			newOrder.setJudgeStatus(infoEntity.getJudgeStatus());
			newOrder.setLogisticsId(infoEntity.getLogisticsId());
			newOrder.setOperator(infoEntity.getOperator());
			BigDecimal tmp = goodsEntity.getGoodsPrice().multiply(new BigDecimal(goodsEntity.getGoodsNumber()));
			newOrder.setOrderAmount(tmp);
			newOrder.setActualAmount(newOrder.getOrderAmount());
			newOrder.setOrderStatus(infoEntity.getOrderStatus());
			newOrder.setPayId(infoEntity.getPayId());
			newOrder.setPayNote(infoEntity.getPayNote());
			newOrder.setPayTime(infoEntity.getPayTime());
			newOrder.setPostscript(infoEntity.getPostscript());
			newOrder.setPayStatus(infoEntity.getPayStatus());
			newOrder.setProcessMode(infoEntity.getProcessMode());
			newOrder.setSellerId(infoEntity.getSellerId());
			newOrder.setShippingFee(infoEntity.getShippingFee());
			newOrder.setShippingId(infoEntity.getShippingId());
			newOrder.setShippingName(infoEntity.getShippingName());
			newOrder.setShippingStatus(infoEntity.getShippingStatus());
			newOrder.setShippingTime(infoEntity.getShippingTime());
			newOrder.setSignBuilding(infoEntity.getSignBuilding());
			newOrder.setTax(infoEntity.getTax());
			newOrder.setTel(infoEntity.getTel());
			newOrder.setWaybill(infoEntity.getWaybill());
			newOrder.setZipcode(infoEntity.getZipcode());
			Integer newOrderId = (Integer) orderDao.create(newOrder);
			goodsEntity.setOrderId(newOrderId);
			ids += ("-"+newOrderId);
		}
		ids = ids.replaceFirst("-", "");
		orderGoodsDao.saveAll(goodsEntities);
		infoEntity.setInvalid(-1);
		orderDao.update(infoEntity);
		return ids;
	}

	@Override
	public boolean doAlipayPay(Map<String, String> filter) {
		System.out.println("orange 回调的支付宝------doAlipayPay::" + filter.toString());
		logger.info("orange 回调的支付宝------doAlipayPay:::" + filter.toString());

		TAlipayCallbackEntity callbackEntity = AlipayController.generateCallbackEntity(filter);

		String orderid = callbackEntity.getOutTradeNo();         // 商品订单号
		BigDecimal totalFee = callbackEntity.getTotalFee();		// 交易金额
		String notifyId = callbackEntity.getNotifyId();        //通知校验id
		callbackEntity.setSubject("商品");

		if(!"TRADE_SUCCESS".equals(callbackEntity.getTradeStatus())){
			return true;
		}
		AlipayCallbackVO vo = JSON.parseObject(callbackEntity.getBody(), AlipayCallbackVO.class);

		String ids = vo.getOrderid();
		ids = ids.replaceAll("-",",");
		List<TOrderInfoEntity> orders = orderDao.queryByIds(ids);
		if(orders==null||orders.isEmpty()){
			return true;
		}
		BigDecimal totalAmount = new BigDecimal(0);
		for (TOrderInfoEntity order : orders){
			totalAmount.add(order.getGoodsAmount());
		}
		if(totalAmount.doubleValue()>totalFee.doubleValue()){
			callbackEntity.setMemo("支付金额不足，订单无法完成");
			alipayCallbackDao.create(callbackEntity);
			if(!"TRADE_SUCCESS".equals(callbackEntity.getTradeStatus())){
				return true;
			}
			for (TOrderInfoEntity order : orders){
				order.setPayStatus(1);
				order.setOrderStatus(3);
				order.setPayId(1);
				order.setPayTime(new Timestamp(System.currentTimeMillis()));
			}
			orderDao.saveAll(orders);
			return true;
		}else{
			alipayCallbackDao.create(callbackEntity);
			if(!"TRADE_SUCCESS".equals(callbackEntity.getTradeStatus())){
				return true;
			}

			// 明细记录
			List<TUserChargeEntity> chargeEntities = new ArrayList<TUserChargeEntity>();
			for (TOrderInfoEntity order : orders){
				TUserChargeEntity chargeEntity = new TUserChargeEntity();
				chargeEntity.setChannel(TUserChargeEntity.ALIBUY);
				chargeEntity.setUserId(order.getUserId());
				chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
				chargeEntity.setValue(order.getOrderAmount());
				chargeEntities.add(chargeEntity);
				order.setPayStatus(1);
				order.setPayTime(new Timestamp(System.currentTimeMillis()));
				order.setPayId(1);
			}
			userChargeDao.saveAll(chargeEntities);
			orderDao.saveAll(orders);

			// 支付成功，清除相应的购物车商品
			List<TOrderGoodsEntity> goods = orderGoodsDao.queryByIds(ids);
			Map<Integer, Integer> priceCount = new HashMap<Integer, Integer>();
			String[] goodsIds = new String[goods.size()];
			Map<Integer, Integer> tmp = new HashMap<Integer, Integer>();
			for(int i = 0; i < goods.size(); i++){
				goodsIds[i] = goods.get(i).getGoodsId().toString();
				priceCount.put(goods.get(i).getPriceId(), goods.get(i).getGoodsNumber());

				if(!tmp.containsKey(goods.get(i).getGoodsId())){
					tmp.put(goods.get(i).getGoodsId(), goods.get(i).getGoodsNumber());
				}else{
					tmp.put(goods.get(i).getGoodsId(), tmp.get(goods.get(i).getGoodsId()) + goods.get(i).getGoodsNumber());
				}
			}

			String ids2 = "";
			for(Integer id: tmp.keySet()){
				ids2+=(","+id);
			}
			ids2 = ids2.replaceFirst(",","");
			List<TGoodsEntity> goodsEntities  = goodsDao.queryByIds(ids2);
			for (TGoodsEntity g : goodsEntities){
				g.setSoldnumber((g.getSoldnumber()==null?0:g.getSoldnumber()) + tmp.get(g.getGoodsId()));
			}
			goodsDao.saveAll(goodsEntities);

			List<TGoodsPriceEntity> priceEntities = goodsPriceDao.queryByGoodsIds(goodsIds);	// 维护数量
			if(priceEntities!=null){
				for (TGoodsPriceEntity price : priceEntities){
					if(priceCount.containsKey(price.getId())){
						if(price.getNumber()==null||price.getNumber()<priceCount.get(price.getId())){
							price.setNumber(0);
						}else{
							price.setNumber(price.getNumber()==null?0:price.getNumber()-priceCount.get(price.getId()));
						}
					}
				}
				goodsPriceDao.saveAll(priceEntities);
			}
			return true;
		}
	}

	@Override
	public boolean doWXPayPay(Map<String, String> filter) {
		System.out.println("orange 回调的微信------doWXPayPay::::" + filter.toString());

		TWxpayCallbackEntity callbackEntity = WXPayController.generateCallbackEntity(filter);

		Integer totalFee = callbackEntity.getTotalFee();
		BigDecimal totalFeeValue = new BigDecimal(totalFee).divide(new BigDecimal(100));
		String nonceStr = callbackEntity.getNonceStr();      // 随机字符串

		if(wxPayCallbackDao.check(nonceStr) > 0){
			return false;
		}

		 // get Attah :  商家数据包
		AlipayCallbackVO vo = JSON.parseObject(callbackEntity.getAttach(), AlipayCallbackVO.class);

		String ids = vo.getOrderid();
		ids = ids.replaceAll("-", ",");

		List<TOrderInfoEntity> orders = orderDao.queryByIds(ids);
		if(orders==null||orders.isEmpty()){
			return true;
		}
		BigDecimal totalAmount = new BigDecimal(0);
		for (TOrderInfoEntity order : orders){
			totalAmount.add(order.getGoodsAmount());
		}

		if(totalAmount.doubleValue()>totalFeeValue.doubleValue()){
			callbackEntity.setErrCodeDes("支付金额不足，订单无法完成");
			wxPayCallbackDao.create(callbackEntity);
			for (TOrderInfoEntity order : orders){
				order.setPayStatus(1);
				order.setOrderStatus(3);
				order.setPayId(2);
				order.setPayTime(new Timestamp(System.currentTimeMillis()));
			}
			orderDao.saveAll(orders);
			return true;
		}else{
			wxPayCallbackDao.create(callbackEntity);
			List<TUserChargeEntity> chargeEntities = new ArrayList<TUserChargeEntity>();
			for (TOrderInfoEntity order : orders){
				order.setPayStatus(1);
				order.setPayTime(new Timestamp(System.currentTimeMillis()));
				order.setPayId(2);
				TUserChargeEntity chargeEntity = new TUserChargeEntity();
				chargeEntity.setChannel(TUserChargeEntity.WXBUY);
				chargeEntity.setUserId(order.getUserId());
				chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
				chargeEntity.setValue(order.getOrderAmount());
				chargeEntities.add(chargeEntity);
			}
			userChargeDao.saveAll(chargeEntities);

			orderDao.saveAll(orders);
			// 支付成功，清除相应的购物车商品
			List<TOrderGoodsEntity> goods = orderGoodsDao.queryByIds(ids);
			Map<Integer, Integer> priceCount = new HashMap<Integer, Integer>();
			String[] goodsIds = new String[goods.size()];

			Map<Integer, Integer> tmp = new HashMap<Integer, Integer>();
			for(int i = 0; i < goods.size(); i++){
				goodsIds[i] = goods.get(i).getGoodsId().toString();
				priceCount.put(goods.get(i).getPriceId(), goods.get(i).getGoodsNumber());
				if(!tmp.containsKey(goods.get(i).getGoodsId())){
					tmp.put(goods.get(i).getGoodsId(), goods.get(i).getGoodsNumber());
				}else{
					tmp.put(goods.get(i).getGoodsId(), tmp.get(goods.get(i).getGoodsId()) + goods.get(i).getGoodsNumber());
				}
			}

			String ids2 = "";
			for(Integer id: tmp.keySet()){
				ids2+=(","+id);
			}
			ids2 = ids2.replaceFirst(",","");
			List<TGoodsEntity> goodsEntities  = goodsDao.queryByIds(ids2);
			for (TGoodsEntity g : goodsEntities){
				g.setSoldnumber((g.getSoldnumber()==null?0:g.getSoldnumber()) + tmp.get(g.getGoodsId()));
			}
			goodsDao.saveAll(goodsEntities);

			List<TGoodsPriceEntity> priceEntities = goodsPriceDao.queryByGoodsIds(goodsIds);		// 维护数量
			if(priceEntities!=null){
				for (TGoodsPriceEntity price : priceEntities){
					if(priceCount.containsKey(price.getId())){
						if(price.getNumber()==null||price.getNumber()<priceCount.get(price.getId())){
							price.setNumber(0);
						}else{
							price.setNumber(price.getNumber()==null?0:price.getNumber()-priceCount.get(price.getId()));
						}
					}
				}
				goodsPriceDao.saveAll(priceEntities);
			}

			// 维护账户记录
			return true;
		}
	}


	// 把用户明细和推荐人明细分开
	@Override
	public boolean doAlipayOneDollarPay(Map<String, String> filter) {
		System.out.println("orange 回调的------doAlipayOneDollarPay:::" + filter.toString());

		TAlipayCallbackEntity callbackEntity = AlipayController.generateCallbackEntity(filter);

		String orderid = callbackEntity.getOutTradeNo();         // 商品订单号
		BigDecimal totalFee = callbackEntity.getTotalFee();		// 交易金额
		String notifyId = callbackEntity.getNotifyId();        //通知校验id
		callbackEntity.setSubject("一元购");

		if(!"TRADE_SUCCESS".equals(callbackEntity.getTradeStatus())){       //交易状态
			return true;
		}

		AlipayCallbackVO vo = JSON.parseObject(callbackEntity.getBody(), AlipayCallbackVO.class);

		TGoodsOnedollarEntity g = goodsOneDollarDao.get(Integer.valueOf(vo.getId()));
		int count = totalFee.intValue() / g.getType();

		List<TOrderOnedollarEntity> orders = orderOneDollarDao.queryByIds(Integer.valueOf(vo.getUserid()), Integer.valueOf(vo.getId()), count);

		// 一元购的用户
		TOrderOnedollarUserEntity orderOnedollarUserEntity = new TOrderOnedollarUserEntity();
		TUserEntity user = userDao.get(Integer.valueOf(orders.get(0).getUserId()));
		orderOnedollarUserEntity.setUserId(user.getUserId());
		orderOnedollarUserEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		orderOnedollarUserEntity.setCount(orders.size());
		orderOnedollarUserEntity.setHead(user.getHead());

		orderOnedollarUserEntity.setNickName(user.getNickName());
		orderOnedollarUserEntity.setOnedollarId(orders.get(0).getOnedollarId());
		orderOneDollarDao.create(orderOnedollarUserEntity);
		for (TOrderOnedollarEntity order: orders){
			order.setPayStatus(1);
			order.setPayType(1);
		}

		orderOneDollarDao.updatePayByIds(Integer.valueOf(vo.getUserid()), Integer.valueOf(vo.getId()), count, 1);

		TGoodsOnedollarEntity goods = goodsOneDollarDao.get(Integer.valueOf(vo.getId()));
		BigDecimal value = null;
		if(goods.getType()==1){		// 一元
			value = new BigDecimal(orders.size());
		}else if(goods.getType()==10){
			value = new BigDecimal(orders.size()*10);
		}

		// 推荐人的操作
		if(user.getReferenceId()!=null&&user.getReferenceId()!=0){

			TUserEntity referenceUser = userDao.get(user.getReferenceId());             //推荐人ID
			BigDecimal bonus = value.multiply(new BigDecimal(0.065)).setScale(2, RoundingMode.DOWN);
			if(bonus.doubleValue()==0){
				bonus = new BigDecimal(0.01);
			}
			referenceUser.setMoney(referenceUser.getMoney() == null ? bonus : referenceUser.getMoney().add(bonus).setScale(2, RoundingMode.DOWN));
			referenceUser.setIncomeNow(referenceUser.getIncomeNow() == null ? bonus : referenceUser.getIncomeNow().add(bonus).setScale(2, RoundingMode.DOWN));
			referenceUser.setIncomeTotal(referenceUser.getIncomeTotal() == null ? bonus : referenceUser.getIncomeTotal().add(bonus).setScale(2, RoundingMode.DOWN));
			userDao.update(referenceUser);

			// 推荐人明细
			TUserChargeEntity chargeEntityBonus = new TUserChargeEntity();
			chargeEntityBonus.setUserId(referenceUser.getUserId());
			chargeEntityBonus.setCreatetime(new Timestamp(System.currentTimeMillis()));
			chargeEntityBonus.setValue(bonus);
			chargeEntityBonus.setType(0);
			chargeEntityBonus.setChannel(6);
			userChargeDao.create(chargeEntityBonus);
		}
		// 当前用户的明细
		String out = "\n\nuserid:"+user.getUserId()+"\nvalue:"+value+"\nChannel:"+TUserChargeEntity.ALIPAY;
		System.out.println(out);

		TUserChargeEntity chargeEntity = new TUserChargeEntity();
		chargeEntity.setUserId(user.getUserId());
		chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		chargeEntity.setValue(value);
		chargeEntity.setType(0);
		chargeEntity.setChannel(TUserChargeEntity.ALIPAY);
		userChargeDao.create(chargeEntity);

		// 判断是不是卖完了，卖完了开奖
		if(orderOneDollarDao.isSoldOut(vo.getId())){

			List<TOnedollarTicketEntity> ticket = oneDollarTicketDao.findBy("onedollarId", Integer.valueOf(vo.getId()));
			if(ticket.size()==0){	// 没有生成奖券
				TOnedollarTicketEntity te = new TOnedollarTicketEntity();
				te.setOnedollarId(Integer.valueOf(vo.getId()));
				te.setWin(1);
				te.setStatus(0);
				// 设置的所有奖券，都是从10000开始的，所以可以查询最后一个的ticketEnd就知道产生了多少个奖券。

				int randomCode = new Random().nextInt(goods.getNeed());		// 生成随机的步长
				te.setCode(10000001+randomCode);
				TOrderOnedollarEntity winner = orderOneDollarDao.queryWinnerOrder(te.getCode(), orderOnedollarUserEntity.getOnedollarId());
				if(winner==null){	// 如果是空的话，容错，随便再找个人
					winner = orderOneDollarDao.queryRandomWinner(orderOnedollarUserEntity.getOnedollarId());
				}
				te.setUserId(winner.getUserId());
				oneDollarTicketDao.create(te);
			}else{
				if(ticket.size()>0){
					List<TOnedollarTicketEntity> t = new ArrayList<TOnedollarTicketEntity>();
					for (int i = 1; i < ticket.size(); i ++){
						ticket.get(i).setWin(0);
						t.add(ticket.get(i));
					}
					if(t.size()>0){
						oneDollarTicketDao.saveAll(t);
					}
				}
			}

			// 卖完了，维护开奖时间
			Calendar c1 = Calendar.getInstance();
			c1.setTime(goods.getTotime());
			c1.add(Calendar.MINUTE, 3);
			goods.setTotime(new Timestamp(c1.getTimeInMillis()));
			goods.setEndtime(goods.getTotime());
			goods.setFill(goods.getNeed());
			goodsOneDollarDao.save(goods);
		}
		return true;
	}

	@Override
	public boolean doWXPayOneDollarPay(Map<String, String> filter) {
		System.out.println("orange 回调的微信------doWXPayOneDollarPay::::" + filter.toString());

		TWxpayCallbackEntity callbackEntity = WXPayController.generateCallbackEntity(filter);

		Integer totalFee = callbackEntity.getTotalFee();
		String nonceStr = callbackEntity.getNonceStr();
		BigDecimal totalFeeValue = new BigDecimal(totalFee).divide(new BigDecimal(100));

		if(wxPayCallbackDao.check(nonceStr) > 0) {
			return false;
		}

		AlipayCallbackVO vo = JSON.parseObject(callbackEntity.getAttach(), AlipayCallbackVO.class);

		TGoodsOnedollarEntity g = goodsOneDollarDao.get(Integer.valueOf(vo.getId()));
		int count = totalFeeValue.intValue()/g.getType();

		List<TOrderOnedollarEntity> orders = orderOneDollarDao.queryByIds(Integer.valueOf(vo.getUserid()), Integer.valueOf(vo.getId()), count);
		TOrderOnedollarUserEntity orderOnedollarUserEntity = new TOrderOnedollarUserEntity();
		TUserEntity user = userDao.get(Integer.valueOf(orders.get(0).getUserId()));
		orderOnedollarUserEntity.setUserId(user.getUserId());
		orderOnedollarUserEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		orderOnedollarUserEntity.setCount(orders.size());
		orderOnedollarUserEntity.setHead(user.getHead());
		orderOnedollarUserEntity.setNickName(user.getNickName());
		orderOnedollarUserEntity.setOnedollarId(orders.get(0).getOnedollarId());
		orderOneDollarDao.create(orderOnedollarUserEntity);
		for (TOrderOnedollarEntity order: orders){
			order.setPayStatus(1);
			order.setPayType(2);
		}
		orderOneDollarDao.updatePayByIds(Integer.valueOf(vo.getUserid()), Integer.valueOf(vo.getId()), count, 2);

		TGoodsOnedollarEntity goods = goodsOneDollarDao.get(Integer.valueOf(vo.getId()));
		BigDecimal value = null;
		if(goods.getType()==1){		// 一元
			value = new BigDecimal(orders.size());
		}else if(goods.getType()==10){
			value = new BigDecimal(orders.size()*10);
		}

		// // 推荐人的操作
		if(user.getReferenceId()!=null&&user.getReferenceId()!=0){
			TUserEntity referenceUser = userDao.get(user.getReferenceId());
			BigDecimal bonus = value.multiply(new BigDecimal(0.065)).setScale(2, RoundingMode.DOWN);
			if(bonus.doubleValue()==0){
				bonus = new BigDecimal(0.01);
			}
			referenceUser.setMoney(referenceUser.getMoney() == null ? bonus : referenceUser.getMoney().add(bonus).setScale(2, RoundingMode.DOWN));
			referenceUser.setIncomeNow(referenceUser.getIncomeNow() == null ? bonus : referenceUser.getIncomeNow().add(bonus).setScale(2, RoundingMode.DOWN));
			referenceUser.setIncomeTotal(referenceUser.getIncomeTotal() == null ? bonus : referenceUser.getIncomeTotal().add(bonus).setScale(2, RoundingMode.DOWN));
			userDao.update(referenceUser);

			TUserChargeEntity chargeEntityBonus = new TUserChargeEntity();
			chargeEntityBonus.setUserId(referenceUser.getUserId());
			chargeEntityBonus.setCreatetime(new Timestamp(System.currentTimeMillis()));
			chargeEntityBonus.setValue(bonus);
			chargeEntityBonus.setType(0);
			chargeEntityBonus.setChannel(6);
			userChargeDao.create(chargeEntityBonus);
		}
		// 当前用户的明细
		String out = "\n\nuserid:"+user.getUserId()+"\nvalue:"+value+"\nChannel:"+TUserChargeEntity.WECHAT;
		System.out.println(out);

		TUserChargeEntity chargeEntity = new TUserChargeEntity();
		chargeEntity.setUserId(user.getUserId());
		chargeEntity.setCreatetime(new Timestamp(System.currentTimeMillis()));
		chargeEntity.setValue(value);
		chargeEntity.setType(1);
		chargeEntity.setChannel(TUserChargeEntity.ALIPAY);
		userChargeDao.create(chargeEntity);

		// 判断是不是卖完了，卖完了开奖
		if(orderOneDollarDao.isSoldOut(vo.getId())){
			List<TOnedollarTicketEntity> ticket = oneDollarTicketDao.findBy("onedollarId", Integer.valueOf(vo.getId()));
			if(ticket.size()==0){	// 没有生成奖券
				TOnedollarTicketEntity te = new TOnedollarTicketEntity();
				te.setOnedollarId(Integer.valueOf(vo.getId()));
				te.setWin(1);
				te.setStatus(0);
				// 设置的所有奖券，都是从10000开始的，所以可以查询最后一个的ticketEnd就知道产生了多少个奖券。

				int randomCode = new Random().nextInt(goods.getNeed());		// 生成随机的步长
				te.setCode(10000001+randomCode);
				TOrderOnedollarEntity winner = orderOneDollarDao.queryWinnerOrder(te.getCode(), orderOnedollarUserEntity.getOnedollarId());
				if(winner==null){	// 如果是空的话，容错，随便再找个人
					winner = orderOneDollarDao.queryRandomWinner(orderOnedollarUserEntity.getOnedollarId());
				}
				te.setUserId(winner.getUserId());
				oneDollarTicketDao.create(te);
			}else{
				if(ticket.size()>0){
					List<TOnedollarTicketEntity> t = new ArrayList<TOnedollarTicketEntity>();
					for (int i = 1; i < ticket.size(); i ++){
						ticket.get(i).setWin(0);
						t.add(ticket.get(i));
					}
					if(t.size()>0){
						oneDollarTicketDao.saveAll(t);
					}
				}
			}

			// 卖完了，维护开奖时间
			Calendar c1 = Calendar.getInstance();
			c1.setTime(goods.getTotime());
			c1.add(Calendar.MINUTE, 3);
			goods.setTotime(new Timestamp(c1.getTimeInMillis()));
			goods.setEndtime(goods.getTotime());
			goods.setFill(goods.getNeed());
			goodsOneDollarDao.save(goods);
		}
		return true;
	}

	@Override
	public Map<String, Object> doJudge(Map<String, String> filter) {
		ResultJson resultJson = JsonChangeUtil.setResultJson("0000", "请求成功");

		String orderid = filter.get("orderid");		// json传递商品参数
		String goodsid = filter.get("goodsid");
		String userid = filter.get("userid");
		String content = filter.get("content");
		String img = filter.get("img");
		String score = filter.get("score");
		TUserEntity user = userDao.get(Integer.valueOf(userid));
		if(user==null||0==user.getStatus()){
			return JsonChangeUtil.setResultJson(ErrorCode.INVALID, "您的账号已失效，请联系我们客服 0755-28383131").getResultMap();
		}
		TOrderInfoEntity order = orderDao.get(Integer.valueOf(orderid));
		if(order.getUserId().intValue()!=Integer.valueOf(userid).intValue()){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}
		if(order.getOrderStatus()!=5||order.getJudgeStatus()!=0){
			return JsonChangeUtil.setResultJson(ErrorCode.NOTAUTHORIZED, "您不能这样做").getResultMap();
		}
		if(order.getIsRefund()!=null&&order.getIsRefund()!=0){
			return JsonChangeUtil.setResultJson(ErrorCode.ORDER_REFOUNDING, "您已经申请过退款").getResultMap();
		}
		TGoodsJudgeEntity entity = new TGoodsJudgeEntity();
//		entity.setMemo(content);
		entity.setAddTime(new Timestamp(System.currentTimeMillis()));
		entity.setOrderId(Integer.valueOf(orderid));
		entity.setStatus(1);
		entity.setContent(content);
		entity.setGoodsId(Integer.valueOf(goodsid));
		entity.setImgUrl(img);
		entity.setScore(new BigDecimal(score));
		entity.setUserId(Integer.valueOf(userid));
		entity.setUpdateTime(entity.getAddTime());
		goodsJudgeDao.create(entity);

		order.setJudgeStatus(1);
		orderDao.update(order);
		return resultJson.getResultMap();
	}


}
